﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace SocketTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 返回收到的字节数
            int nRetByte;
            byte[] data = new byte[1024];
            // IPEndPoint 将网络终结点表示为IP地址和端口号
            // IPAddress 提供网络协议IP地址
            IPEndPoint IPep = new IPEndPoint(IPAddress.Any,9050);
            // 实现 Berkeley套接字接口
            // AddressFamily:指定Socket类实例可以使用的寻址方案;
            // InterNetwork:IPV4版本的地址
            // SocketType:套集字类型;Stream:基于TCP的字节流类型
            // ProtocolType:协议的类型
            Socket newSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            // 使Socket与一个本地终结点相连
            newSocket.Bind(IPep);
            // 使Socket与处于监听状态
            newSocket.Listen(10);
            Console.WriteLine("Wait for a Client");
            // 为新建连接创建新的Socket
            Socket ClientSocket = newSocket.Accept();
            // RemoteEndPoint:获取远程终结点
            IPEndPoint ClientTip = (IPEndPoint)ClientSocket.RemoteEndPoint;
            Console.WriteLine("Connect with Client:"+ ClientTip.Address + "at Port:"+ ClientTip.Port);
            string strWelcome = "Welcome to Server,You Can Send Data To Server";
            // 获取ASCII字符集的编码
            // GetBytes将指定字符串中所有的字符编码为一个字节序列
            data = Encoding.ASCII.GetBytes(strWelcome);
            // 将数据发送到Socket
            ClientSocket.Send(data);
            while (true)
            {
                data = new byte[1024];
                // 从绑定的套接字接受数据,将数据存入接受缓冲区
                nRetByte = ClientSocket.Receive(data);
                Console.WriteLine("Receive Data from Client, Data Size is {0} Bit",nRetByte);
                if (nRetByte == 0)
                    break;
                Console.WriteLine(Encoding.ASCII.GetString(data,0,nRetByte));

                string strInput = Console.ReadLine();
                if (strInput == "exit")
                    break;

                String strSay = "Server Say:";
                ClientSocket.Send(Encoding.ASCII.GetBytes(strSay + strInput));
                Console.WriteLine(strInput);
            }
            Console.WriteLine("DisConnect from ClientAddress",ClientTip.Address);
            ClientSocket.Close();
            newSocket.Close();
        }
    }
}
